package com.incon.common.interceptor;
import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.incon.pojo.UserEntity;
import com.incon.project.hello.service.UserService;

/**
 * 从数据库中读入用户的密码，角色信息，是否锁定，账号是否过期等
 *
 */
public class MyUserDetailService implements UserDetailsService {
    @Resource
    private UserService userService;
//    @Autowired
//    private UserCache userCache;
    /**
     * 数据库交互获取用户拥有的权限角色，并设置权限
     */
    @Override
    public UserDetails loadUserByUsername(String userCode) throws UsernameNotFoundException, DataAccessException {
        // 根据登录用户名获取用户信息
    	UserEntity user = new UserEntity();
        user.setUsername(userCode);
        user.setPassword("X");

      //  user = userService.selectByModel(user);
        System.out.println("用户登录"+this.getClass().getSimpleName());
        if (null != user) {
            // 存放权限
        	;
            Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
            String action = "ROLE_USER, ROLE_ADMIN";
                if (userCode.equals("admin")){
                     action =   "ROLE_ADMIN"   ;
                }else{
                	 action =   "ROLE_USER"   ;
                }
                if (StringUtils.isNotBlank(action)) {
                    String[] roleaCtion = action.split(",");
                    for (int i = 0; i < roleaCtion.length; i++) {
                        SimpleGrantedAuthority auth = new SimpleGrantedAuthority(roleaCtion[i]);
                        auths.add(auth);
                    }
                }
                //spring security自带的User对象
            User userDetails = new User(userCode, user.getPassword(), true, true, true, true, auths);
            return userDetails;
        }
        return null;
    }
}